package io.summer.basis.tool;

import io.summer.basis.excepts.AppException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Moonlight
 */
@Component
public final class HttpTool {
  private static final Logger log = LoggerFactory.getLogger(HttpTool.class);
  private static OkHttpClient okHttpClient;
  private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");

  @Autowired
  public HttpTool(OkHttpClient client) {
    okHttpClient = client;
  }

  public static OkHttpClient client() {
    return okHttpClient;
  }

  public static byte[] post(String url, Object bodyData) {
    Request request = new Request.Builder().url(url).post(
      bodyData == null ?
        Util.EMPTY_REQUEST : RequestBody.create(JSON_TYPE, ObjectTool.serialize(bodyData))
    ).build();
    try {
      Response response = okHttpClient.newCall(request).execute();
      if (!response.isSuccessful()) {
        log.error("[HttpTool] post failed: {}", response.code());
      } else {
        ResponseBody body = response.body();
        if (body != null) {
          return body.bytes();
        }
      }
    } catch (IOException e) {
      throw new AppException(e);
    }
    return new byte[0];
  }
}
